#include "client.h"
#include "debug/logger.h"

namespace renderit {
	namespace client {

		windows_client::windows_client()
			: iclient()
			, main_window_(nullptr)
			, last_tick_time_(0)
			, is_exit_(false)
			, console_(nullptr)
		{
			game_start_time_ = time();
			last_tick_time_ = game_start_time_;
		}

		windows_client::~windows_client()
		{
			if (main_window_) {
				delete main_window_;
				main_window_ = nullptr;
			}
		}

		iwindow * windows_client::create_window(uint32 width, uint32 height, const std::string& title)
		{
			window * w = window::create(width, height, title);
			if (!main_window_)
			{
				main_window_ = w;
			}
			w->show(true);
			windows_.push_back(w);
			return w;
		}

		double windows_client::time()
		{
			LARGE_INTEGER tm;
			LARGE_INTEGER frequence;

			::QueryPerformanceFrequency(&frequence);
			::QueryPerformanceCounter(&tm);

			return tm.QuadPart * 1.0f / frequence.QuadPart;
		}

		iconsole * windows_client::create_console(const std::string& title)
		{
			console_ = new console(title);
			return console_;
		}

		bool windows_client::loop()
		{
			bool b = true;
			// 1. if has windows
			if (main_window_) {
				// loop main window
				b = main_window_->loop();

				// loop other windows
				for (int i = 1; i < windows_.size(); ++i)
				{
					if (windows_[i])
					{
						windows_[i]->loop();
					}
				}
			}
			// 2. otherwise
			else 
			{
				b = !is_exit_;
			}

			if (!b)
			{
				// TODO : Last Frame
			}
			else
			{
				double t = time();
				last_tick_time_ = t;

				// Do Console Inputs
				if (console_)
				{
					console_->do_input();					
				}
			}
			return b;
		}

		void windows_client::exit()
		{
			is_exit_ = true;
			::PostQuitMessage(0);
		}
	}
}